// More or less the same as a user's permissions.

import { Schema, default as mongoose } from 'mongoose';
import { PermissionsSchemaObject, defaultUserPermissions } from '../perms';
export {
  PermissionsSchemaObject,
  defaultUserPermissions,
  UserPermission as UserPermissions,
} from '../perms';

export const PermissionGroupSchema = new Schema({
  groupName: { type: String, index: true, required: true },
  permissions: PermissionsSchemaObject,
});
// function declared like this as a result of `this` keyword :/
PermissionGroupSchema.pre('save', function (next, opts) {
  const t = this;
  t.permissions = t.permissions ?? {};
  Object.entries(defaultUserPermissions).forEach(
    ([k, v]) =>
      (t.permissions![k as keyof typeof t.permissions] =
        t.permissions![k as keyof typeof t.permissions] ?? v),
  );
  next();
});
export const PermissionGroupModel = mongoose.model(
  'PermGroup',
  PermissionGroupSchema,
);
export default PermissionGroupModel;
